package com.zcp.pcsuitall;

import java.io.IOException;
import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;

import org.xmlpull.v1.XmlSerializer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.util.Log;
import android.util.Xml;

/**
 * 接收短信并主动上报
 *
 */
public class DeliverReceive extends BroadcastReceiver {
	
	private static final String TAG = "DeliverReceive";
	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
    	
    	Log.i(TAG, "DeliverReceive begin.");
    	if (intent.getAction().equals(SMS_RECEIVED)) {
    		
    		Bundle bundle = intent.getExtras();
    		String address = null;
    		String body = null;
    		
    		if (bundle != null) {
	    		Object[] pdus = (Object[]) bundle.get("pdus");
	    		SmsMessage[] msg = new SmsMessage[pdus.length];
	    		for (int i = 0; i < pdus.length; i++) {
	    			msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
	    		}
	    		System.out.println(msg.length+"--msg leng");
	    		StringBuffer sb = new StringBuffer();
	    		for (SmsMessage currMsg : msg) {
		    		address = currMsg.getDisplayOriginatingAddress();//手机号
		    		sb.append(currMsg.getDisplayMessageBody());
		    		
	    		}
	    		body = sb.toString();
	    		SmsContent content = new SmsContent(new Handler(),context,new String[]{address,body});  
	    		context.getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, content);
	    		
    		}
    		
    	}	
    }
    
    class SmsContent extends ContentObserver{  
        private Cursor cursor = null;  
        Context mContext;
        String []str;
        
        public SmsContent(Handler handler, Context mContext,String[] addressAndBody) {
			super(handler);
			this.mContext = mContext;
			str = addressAndBody;
		}

		public SmsContent(Handler handler) {  
            super(handler);  
        }  
          
        @Override  
        public void onChange(boolean selfChange) {  
            // TODO Auto-generated method stub  
        	Log.i(TAG,"sms database onchange");
        	super.onChange(selfChange);  
        	
        	if(str == null){
        		return;
        	}
        	
            int id = 0;
            String address = str[0];
            String body = str[1];
            String date = null;
            Date dateTime = new Date(0l);
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		Log.i(TAG,"begin address="+address+"--body="+body+"--id"+id);
    		
    		cursor = mContext.getContentResolver().query(Uri.parse("content://sms/inbox"), null, "address='"+address+"' and body='"+body.replace("'", "''")+"'", null,"date desc");  
            
            if (cursor != null){
               try{
            	   if(cursor.moveToFirst()) {
            		   id = cursor.getInt(cursor.getColumnIndex("_id"));
            		   dateTime.setTime(cursor.getLong(cursor.getColumnIndex("date")));
            		   date = dateFormat.format(dateTime);
            		   Log.i(TAG, "SMS RECEIVE DATE FORMAT:"+date);
   					}
               }catch (Exception e) {
	    			e.printStackTrace();
	    		}finally{
	    			cursor.close();
	    		}
               
               Log.i(TAG,"end address="+address+"--body="+body+"--id"+id);
               StringWriter writer = new StringWriter();
               XmlSerializer serializer = Xml.newSerializer();
	    		try {
					Intent dataIntent = new Intent(SocketService.DELIVER_MESSAGE_REPORT_ACTIOIN);
					Action action = new Action("HaveMessage", null);
			        serializer.setOutput(writer);
		            XmlDataDealWith.createPre(action, serializer);
		            serializer.startTag(null, "item");
		            writeSingleTextToXml(serializer, "id", id+"");
		            writeSingleTextToXml(serializer, "thread_id", null);
		            writeSingleTextToXml(serializer, "address", address);
		            writeSingleTextToXml(serializer, "person_id", null);
		            writeSingleTextToXml(serializer, "date", date);
		            writeSingleTextToXml(serializer, "protocol", null);
		            writeSingleTextToXml(serializer, "is_read", null);
		            writeSingleTextToXml(serializer, "status", null);
		            writeSingleTextToXml(serializer, "type", "1");
		            writeSingleTextToXml(serializer, "reply_path_present", null);
		            writeSingleTextToXml(serializer, "subject", null);
		            writeSingleTextToXml(serializer, "body", body);
		            writeSingleTextToXml(serializer, "service_center", null);
		            writeSingleTextToXml(serializer, "locked", null);
		            serializer.endTag(null, "item");
		            serializer.text("");
		            serializer.endTag("", "data");
		            serializer.endTag("", "root");
		            serializer.endDocument();
		            System.out.println("receive xml value:"+writer.toString());
					dataIntent.putExtra(SocketService.SEND_DATA_KEY,writer.toString());
					mContext.sendBroadcast(dataIntent);//向SocketService(SEND_DATA_ACTIOIN)上报短信
					
					str = null;
					mContext.getContentResolver().unregisterContentObserver(this);
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    		}
            }  
        }  
        
        /**
         * 创建一个包含单个值的XML节点，如<TAG>value</TAG>,写入serializer中
         */
        private void writeSingleTextToXml(XmlSerializer serializer, String tag, String value)
                throws IllegalArgumentException, IllegalStateException, IOException {
            // 值为空时不写入XML
            if (value == null)
                value = "";
            serializer.startTag(null, tag);
            serializer.text(value);
            serializer.endTag(null, tag);
        }
    }  
      
}